
package coop.bancocredicoop.proyectos.gd.alfresco

import org.apache.http.client.utils.URIBuilder
import org.apache.http.impl.client.HttpClients
import org.apache.http.client.methods.HttpGet
import org.apache.http.client.methods.HttpPost
import org.apache.http.impl.client.BasicResponseHandler

import groovy.json.JsonSlurper

class AlfrescoServiceConnection {

    def alfrescoConfig  

    AlfrescoServiceConnection(alfrescoConfig) {
        this.alfrescoConfig = alfrescoConfig
    }

    def getClient(clientParams) {
        def authType = alfrescoConfig.authentication.type
        if (authType == 'explorer') {
            getClientWithExplorer(clientParams.loggedInUser)
        } else if (authType == 'cas+explorer') {
            getClientWithCASAndExplorer(clientParams.loggedInUser)
        } else {
            getClientWithAlfTicket()
        } 
    }

    private def getClientWithAlfTicket() {
        def serviceURL = "${alfrescoConfig.baseURL}${alfrescoConfig.serviceURL}"
        def loginURL = new URIBuilder(serviceURL + '/api/login')
        def user = alfrescoConfig.credentials.user
        def password = alfrescoConfig.credentials.password
        URI uri = loginURL
		                .setParameter("u", user)
		                .setParameter("pw", password)
		                .build()
        def httpclient = HttpClients.createDefault()
        try {
            def httpget = new HttpGet(uri)
            // TODO: Handle errors
            def response = httpclient.execute(httpget)    
            def ticket = new XmlSlurper().parse(response.getEntity().getContent())
            response.close()
        } finally {
            httpclient.close() 
        }
        new AlfrescoHttpClientWithAlfTicket(alfrescoConfig, ticket.text())
    }

    private def getClientWithCASAndExplorer(user) {
        new AlfrescoHttpClientWithCASAndExplorer(alfrescoConfig, user)
    }

    private def getClientWithExplorer(user) {
        new AlfrescoHttpClientWithExplorer(alfrescoConfig, user)
    }

}


